/**
 * 上海中赢金融信息服务有限公司
 * Copyright (c) 2017-2027 Chinazyjr,Inc.All Rights Reserved.
 */

package com.sys.midware.mongo.core.index;

import java.util.LinkedHashMap;
import java.util.Map;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;

/**
 * <b>ClassName:</b> Index.java <br/>
 * <b>Description:</b> TODO <br/>
 * <b>Date:</b> 2016年2月22日 下午1:29:46<br/>
 * 
 * @author mobing
 * @version
 */
public class MongoIndex {
    enum Duplicates {
        RETAIN(0), DROP(1);
        private int duplicateVal;

        private Duplicates(int duplicateVal) {
            this.duplicateVal = duplicateVal;
        }

        public int getDuplicateVal() {
            return duplicateVal;
        }

        public void setDuplicateVal(int duplicateVal) {
            this.duplicateVal = duplicateVal;
        }

    }

    private final Map<String, MongoIndexOrder> fieldSpec;

    private String name;

    private boolean unique;

    private boolean dropDuplicates;

    private boolean sparse;

    public MongoIndex() {
        fieldSpec = new LinkedHashMap<String, MongoIndexOrder>();
        unique = false;
        dropDuplicates = false;
        sparse = false;
    }

    public MongoIndex(String key, MongoIndexOrder order) {
        fieldSpec = new LinkedHashMap<String, MongoIndexOrder>();
        unique = false;
        dropDuplicates = false;
        sparse = false;
        fieldSpec.put(key, order);
    }

    public MongoIndex on(String key, MongoIndexOrder order) {
        fieldSpec.put(key, order);
        return this;
    }

    public MongoIndex named(String name) {
        this.name = name;
        return this;
    }

    public MongoIndex unique() {
        unique = true;
        return this;
    }

    public MongoIndex sparse() {
        sparse = true;
        return this;
    }

    public MongoIndex unique(Duplicates duplicates) {
        if (duplicates == Duplicates.DROP)
            dropDuplicates = true;
        return unique();
    }

    public DBObject getIndexOptions() {
        if (name == null && !unique)
            return null;
        DBObject dbo = new BasicDBObject();
        if (name != null)
            dbo.put("name", name);
        if (unique)
            dbo.put("unique", Boolean.valueOf(true));
        if (dropDuplicates)
            dbo.put("dropDups", Boolean.valueOf(true));
        if (sparse)
            dbo.put("sparse", Boolean.valueOf(true));
        return dbo;
    }

    public DBObject getIndexKeys() {
        DBObject dbo = new BasicDBObject();
        for (Map.Entry<String, MongoIndexOrder> entry : fieldSpec.entrySet()) {
            dbo.put(entry.getKey(), entry.getValue().getOrderValue());
        }

        return dbo;
    }

    public String toString() {
        return String.format("Index: %s - Options: %s", new Object[] { getIndexKeys(), getIndexOptions() });
    }
}
